use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::{
    components::{Route, Router, Routes},
    StaticSegment,
};

mod pages;

use pages::*;

pub fn shell(options: LeptosOptions) -> impl IntoView {
    view! {
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <AutoReload options=options.clone() />
                <HydrationScripts options />
                <MetaTags />
            </head>
            <body>
                <App />
            </body>
        </html>
    }
}

#[component]
pub fn App() -> impl IntoView {
    // 提供管理样式表、标题、元标签等的上下文
    provide_meta_context();

    view! {
        <Stylesheet id="leptos" href="/pkg/conferris.css" />

        // 设置文档标题
        <Title text="Welcome to Conferris" />

        // 欢迎页内容
        <Router>
            <main>
                <Routes fallback=|| view! { <SimplePageNotFound /> }>
                    <Route path=StaticSegment("") view=HomePage />
                </Routes>
            </main>
        </Router>
    }
}

/// 渲染应用的首页。
#[component]
fn HomePage() -> impl IntoView {
    // 创建响应式值以更新按钮
    let count = RwSignal::new(0);
    let on_click = move |_| *count.write() += 1;

    // 创建服务器函数测试状态
    let test_result = RwSignal::new("Click to test server function".to_string());
    
    // 测试服务器函数
    let test_server = move |_| {
        leptos::task::spawn_local(async move {
            match test_server_function().await {
                Ok(result) => {
                    leptos::logging::log!("Server function success: {}", result);
                    test_result.set(result)
                },
                Err(e) => {
                    leptos::logging::error!("Server function error: {}", e);
                    test_result.set(format!("Error: {}", e))
                },
            }
        });
    };

    // 浏览器控制台日志示例
    let log_example = move |_| {
        leptos::logging::log!("这是一条普通日志 (log)");
        leptos::logging::warn!("这是一条警告日志 (warn)");
        leptos::logging::error!("这是一条错误日志 (error)");
        leptos::logging::debug_warn!("这是一条调试警告 (debug_warn)");
    };

    view! {
        <h1>"Welcome to Conferris!"</h1>
        <button class="btn btn-primary btn-sm" on:click=on_click>
            "Click Me: "
            {count}
        </button>

        <div class="flex gap-2 mt-4">
            <button class="btn btn-secondary btn-sm" on:click=test_server>
                "Test Server Function"
            </button>
            <button class="btn btn-accent btn-sm" on:click=log_example>
                "Console Log Test"
            </button>
        </div>

        <p class="mt-2">"Result: " {test_result}</p>
        <ComplexInput />
    }
}

/// 测试服务器函数 - 验证 entity/ssr 不影响 #[server] 功能
#[server]
async fn test_server_function() -> Result<String, ServerFnError> {
    // 这个函数会在服务器端执行，可以使用 entity crate
    // 但前端 WASM 中只包含调用接口，不包含实现代码
    
    // 在服务器端打印日志 - #[server] 宏自动处理条件编译
    tracing::info!("测试服务器函数被调用 - 开始执行");
    
    // 模拟一些工作
    tracing::debug!("执行一些服务器端逻辑...");
    
    // 这里可以添加数据库操作（使用 entity crate）
    // 例如：let posts = entity::Post::find().all(&db).await?;
    
    tracing::info!("测试服务器函数执行完成");
    
    Ok("Server function works!".to_string())
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
struct Settings {
    display_name: String,
}

#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
struct HeftyData {
    first_name: String,
    last_name: String,
    settings: Settings,
}

#[component]
fn ComplexInput() -> impl IntoView {
    let submit = ServerAction::<VeryImportantFn>::new();

    view! {
        <ActionForm action=submit>
            <input class="input" type="text" name="hefty_arg[first_name]" value="leptos" />
            <br />
            <input
                class="input"
                type="text"
                name="hefty_arg[last_name]"
                value="closures-everywhere"
            />
            <br />
            <input
                class="input"
                type="text"
                name="hefty_arg[settings][display_name]"
                value="my alias"
            />
            <br />
            <input class="btn btn-primary" type="submit" />
        </ActionForm>
    }
}

#[server]
async fn very_important_fn(hefty_arg: HeftyData) -> Result<(), ServerFnError> {
    assert_eq!(hefty_arg.first_name.as_str(), "leptos");
    assert_eq!(hefty_arg.last_name.as_str(), "closures-everywhere");
    assert_eq!(hefty_arg.settings.display_name.as_str(), "my alias");
    tracing::info!("very_important_fn 被调用 - 参数: {:?}", hefty_arg);
    
    use sea_orm::prelude::*;
    use entity::prelude::*;

    let db = use_context::<DatabaseConnection>().unwrap();

    let posts = Post::find().all(&db).await?;
    tracing::info!("数据库中的帖子: {:?}", posts);
    Ok(())
}